%%%-------------------------------------------------------------------
%%% File    : rdf_store.erl
%%% Author  :  <vjache>
%%% Description : 
%%%
%%% Created : 26 May 2009 by  <vjache>
%%%-------------------------------------------------------------------

-module(prc_util).

%%-------------------------------------------------------------------
%% Include files
%%-------------------------------------------------------------------

%%-------------------------------------------------------------------
%% Exported Functions
%%-------------------------------------------------------------------
-export([
		 wait_finish/1,
		 wait_finish_ex/1
		 ]).

%%-------------------------------------------------------------------
%% API Functions
%%-------------------------------------------------------------------
wait_finish(Pid) when is_pid(Pid)->
	Ref=erlang:monitor(process, Pid),
	receive
		{'DOWN', Ref, _Type, _Object, normal} ->
			ok;
		{'DOWN', Ref, _Type, Object, Info} ->
			throw({error,{prc_failed,Object,Info}})
	end;
wait_finish(Pids) when is_list(Pids)->
	Refs=[erlang:monitor(process, Pid)||Pid<-Pids],
	wf_rc_loop(Refs,[]).
wait_finish_ex(PidFunList) when is_list(PidFunList)->
	RefFunList=[{erlang:monitor(process, Pid),Fun}||{Pid,Fun}<-PidFunList],
	wfex_rc_loop(RefFunList).

%%-------------------------------------------------------------------
%% Local Functions
%%-------------------------------------------------------------------

wf_rc_loop([],[]) ->
	ok;
wf_rc_loop([],Errors) ->
	throw({errors,Errors});
wf_rc_loop([Ref|Tail]=_Refs,Errors) ->
	receive
		{'DOWN', Ref, _Type, _Object, normal} ->
			wf_rc_loop(Tail,Errors);
		{'DOWN', Ref, _Type, Object, Info} ->
			wf_rc_loop(Tail,[{prc_failed,Object,Info}|Errors])
	end.
wfex_rc_loop([]) ->
	ok;
wfex_rc_loop(RefFunList) ->
	receive
		{'DOWN', Ref, _Type, _Object, _Info} ->
			{value,{Ref,Fun},RefFunList1}=lists:keytake(Ref, 1, RefFunList),
			Fun(),
			wfex_rc_loop(RefFunList1)
	end.

